﻿//------------------------------------------------------------------------------
// System Name:    Customer Service Platform
// Component:      Customer Management Page
// Created By:     Tingrong Shi (trshi@wicresoft.com)
// Created Date:   2011-3-16
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASB.CC.Business.CIS;
using ASBCC.Business;
using ASBCC.Business.CIS;
using ASBCC.Database.EntityFramework;
using System.Web.Services;

namespace ASB.CC.Web.CIS2.Shared
{
    public partial class CustomerInfo : EntityPage
    {
        /// <summary>
        /// CID Customers Page
        /// </summary>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["companyid"] != null)
                    BtnAdd_Click(null, EventArgs.Empty);
                string customerID = Request.QueryString["view"];
                if (!String.IsNullOrEmpty(customerID))
                {
                    DVCustomer.ChangeMode(DetailsViewMode.ReadOnly);
                    CurrentMode = EntityMode.Detail;
                }
            }
        }

        protected override EntityDataSource EntitySource
        {
            get { return this.edsCustomer; }
        }

        protected override TextBox EntitySearchTxt
        {
            get { return this.SearchText; }
        }

        protected override Button EntityAddBtn
        {
            get { return this.btnAdd; }
        }
        protected override Button EntitySearchBtn
        {
            get { return this.Searchbtn; }
        }
        protected override Button EntityClearBtn
        {
            get { return this.Cleanbtn; }
        }

        protected override GridView EntityGrid
        {
            get { return this.GVCustomer; }
        }

        protected override DetailsView EntityDetails
        {
            get { return this.DVCustomer; }
        }

        protected override void OnEntityDisabling(int entityKey)
        {
            CustomerManageHelper.SetCustomerDisabled(entityKey);
            GlobalHelper.LogOperation(this.User.Identity.Name, SystemModule.CID, "Customer disabled. id=" + entityKey + "; name=" + CustomerManageHelper.getName(entityKey));
        }

        protected override string GetEntityWhereExpression(string keyword)
        {
            string companyIDfilter = "";
            var cid = this.Request.QueryString["CID"];
            if (!string.IsNullOrEmpty(cid))
                companyIDfilter = " and it.Company.CompanyID=" + cid; //" and it.CustomerID in { " + cid1 + " }";

            string customerIDfilter = "";
            var custometID = this.Request.QueryString["CustomerID"];
            if (!string.IsNullOrEmpty(custometID))
                companyIDfilter = " and it.CustomerID=" + custometID;

            string roles = (User as CSPrincipal).Role2String;
            UserRoles ur = LoadRoles();

            //this.edsCompany.Where = "!it.Disabled and it.CompanyID in {" + CustomerManageHelper.GetCompanyByRoleID((User as CSPrincipal).Role2String) + "}";

            string companyWhere = "!it.Disabled ";
            companyWhere += " and ( (Count( select value pc.Province.ProvinceID from it.PCATs as pc where !pc.Province.Disabled and !pc.Category.Disabled and ";
            companyWhere += string.Format("Count( select value r.RoleID from pc.Roles as r where !r.Disabled and r.RoleID in {{{0}}} ) > 0 ) > 0 ", roles);
            companyWhere += " or Count( select value cu.CountryID from it.Countries as cu where !cu.Disabled and ";
            companyWhere += string.Format("Count( select value r.RoleID from cu.Roles as r where !r.Disabled and r.RoleID in {{{0}}} ) > 0 ) > 0 )", roles);
            if (ur.IsDomesticAdmin)
            {
                companyWhere += " or Count( select value pc.Province.ProvinceID from it.PCATs as pc where !pc.Province.Disabled and !pc.Category.Disabled ) > 0";
            }
            if (ur.IsOverseaAdmin)
            {
                companyWhere += " or Count( select value cu.CountryID from it.Countries as cu where !cu.Disabled ) > 0";
            }
            companyWhere += " ) ";

            this.edsCompany.Where = companyWhere;

            edsCompany.DataBind();



            //var filter = "it.Name like N'%" + keyword + "%' and !it.Disabled ";
            //filter += " and it.CustomerID in {" + CustomerManageHelper.GetCustomerIDbyRoleID((User as CSPrincipal).Role2String) + "}";



            //filter += "and Count( select value pc.Province.ProvinceID from it.Company.PCATs as pc where !it.Company.Disabled and !pc.Province.Disabled and !pc.Category.Disabled and ";
            //filter += "Count( select value r.RoleID from pc.Roles as r where !r.Disabled and r.RoleID in {{{0}}} ) > 0 ) > 0";
            //filter = string.Format(filter, (User as CSPrincipal).Role2String);



            string customerWhere = "it.Name like N'%" + keyword + "%' and !it.Disabled ";
            customerWhere += "and ( (Count( select value pc.Province.ProvinceID from it.Company.PCATs as pc where !it.Company.Disabled and !pc.Province.Disabled and !pc.Category.Disabled and ";
            customerWhere += string.Format("Count( select value r.RoleID from pc.Roles as r where !r.Disabled and r.RoleID in {{{0}}} ) > 0 ) > 0", roles);
            customerWhere += " or Count( select value cu.CountryID from it.Company.Countries as cu where !it.Company.Disabled and !cu.Disabled and ";
            customerWhere += string.Format("Count( select value r.RoleID from cu.Roles as r where !r.Disabled and r.RoleID in {{{0}}} ) > 0 ) > 0 )", roles);
            if (ur.IsDomesticAdmin)
            {
                customerWhere += " or Count( select value pc.Province.ProvinceID from it.Company.PCATs as pc where !it.Company.Disabled and !pc.Province.Disabled and !pc.Category.Disabled ) > 0";
            }
            if (ur.IsOverseaAdmin)
            {
                customerWhere += " or Count( select value cu.CountryID from it.Company.Countries as cu where !it.Company.Disabled and !cu.Disabled ) > 0";
            }
            customerWhere += " ) ";
            customerWhere += companyIDfilter;
            customerWhere += customerIDfilter;

            string customerID = Request.QueryString["view"];
            if (!String.IsNullOrEmpty(customerID))
            {
                edsCustomer.Where = "it.CustomerID = " + customerID;
                edsCustomer.DataBind();
            }

            return customerWhere;
        }

        protected override void OnEntityInserting(EntityDataSourceChangingEventArgs e)
        {
            var dc = e.Context;
            var customer = e.Entity as ASBCC.Database.EntityFramework.Customer;

            customer.Level = Convert.ToInt32(this.Request.Form["Level"]);
            if (!String.IsNullOrEmpty(this.Request.Form["BirthdayText"]))
                customer.Birthday = Convert.ToDateTime(this.Request.Form["BirthdayText"]);
            var gen = Request.Form["Genderselect"];
            if (gen == "0")
                customer.Gender = null;
            if (gen == "1")
                customer.Gender = true;
            if (gen == "2")
                customer.Gender = false;
            var companyID = Convert.ToInt32(this.Request.Form["Companyselect"]);
            var companies = dc.CreateQuery<Company>("Companies");
            customer.Company = companies.First(p => p.CompanyID == companyID);
            var employeeNo = CustomerManageHelper.GetEmployeeNoByName(this.User.Identity.Name);
            var Employees = dc.CreateQuery<Employee>("Employees");
            customer.CreateBy = Employees.First(p => p.EmployeeNo == employeeNo);
            customer.CreateTime = DateTime.Now;
            customer.LastModifyBy = Employees.First(p => p.EmployeeNo == employeeNo);
            customer.LastModifyTime = DateTime.Now;
            var dep = this.Request.Form["Departmentselect"];
            if (!String.IsNullOrEmpty(dep) && dep != "-1")
            {
                int departmentID = 0;
                if (!int.TryParse(dep, out departmentID))
                    departmentID = CustomerManageHelper.InsertNewDepartment(dep);
                else
                    departmentID = Convert.ToInt32(dep);
                var Departments = dc.CreateQuery<CustomerDepartment>("CustomerDepartments");
                customer.CustomerDepartment = Departments.First(p => p.DepartmentID == departmentID);
            }
            var def = this.Request.Form["Definitionselect"];
            if (!String.IsNullOrEmpty(def))
            {
                var defID = Convert.ToInt32(this.Request.Form["Definitionselect"]);
                var definitions = dc.CreateQuery<Definition>("Definitions");
                customer.Definition = definitions.First(p => p.DefID == defID);
            }

            var edu = new EducationSource();
            edu.School = this.Request.Form["Educations-school"];
            edu.Degree = this.Request.Form["Educations-degree"];
            edu.Description = this.Request.Form["Educations-description"];

            var fam = new FamilySource();
            fam.Name = this.Request.Form["FamilyInfo-name"];
            fam.Relationship = this.Request.Form["FamilyInfo-relationship"];
            fam.WorkPlace = this.Request.Form["FamilyInfo-workPlace"];
            fam.Description = this.Request.Form["FamilyInfo-description"];

            var wor = new WorkExprienceSource();
            wor.CompanyName = this.Request.Form["WorkExperience-name"];
            wor.Title = this.Request.Form["WorkExperience-title"];
            wor.StartTime = this.Request.Form["WorkExperience-starttime"];
            wor.EndTime = this.Request.Form["WorkExperience-endtime"];
            wor.Description = this.Request.Form["WorkExperience-description"];

            var pre = new PreferenceSource();
            pre.List = this.Request.Form["preferenceList"];
            pre.Value = this.Request.Form["preferenceValue"];
            pre.Level = this.Request.Form["preferenceLevel"];

            CustomerManageHelper.OnCustomerInserting(customer,null, edu, fam, wor, pre, dc);
        }

        protected override void OnEntityUpdating(EntityDataSourceChangingEventArgs e)
        {
            var dc = e.Context;
            var customer = e.Entity as Customer;
            customer.Level = Convert.ToInt32(this.Request.Form["Level"]);
            if (!String.IsNullOrEmpty(this.Request.Form["BirthdayText"]))
                customer.Birthday = Convert.ToDateTime(this.Request.Form["BirthdayText"]);
            var gen = Request.Form["Genderselect"];
            if (gen == "0")
                customer.Gender = null;
            if (gen == "1")
                customer.Gender = true;
            if (gen == "2")
                customer.Gender = false;
            var companyID = Convert.ToInt32(this.Request.Form["Companyselect"]);
            var companies = dc.CreateQuery<Company>("Companies");
            customer.Company = companies.First(p => p.CompanyID == companyID);
            var employeeNo = CustomerManageHelper.GetEmployeeNoByName(this.User.Identity.Name);
            var Employees = dc.CreateQuery<Employee>("Employees");
            customer.LastModifyBy = Employees.First(p => p.EmployeeNo == employeeNo);
            customer.LastModifyTime = DateTime.Now;
            var dep = this.Request.Form["Departmentselect"];
            if (!String.IsNullOrEmpty(dep) && dep != "-1")
            {
                int departmentID = 0;
                if (!int.TryParse(dep, out departmentID))
                    departmentID = CustomerManageHelper.InsertNewDepartment(dep);
                else
                    departmentID = Convert.ToInt32(dep);
                var Departments = dc.CreateQuery<CustomerDepartment>("CustomerDepartments");
                customer.CustomerDepartment = Departments.First(p => p.DepartmentID == departmentID);
            }
            var def = this.Request.Form["Definitionselect"];
            if (!String.IsNullOrEmpty(def))
            {

                var defID = Convert.ToInt32(this.Request.Form["Definitionselect"]);
                var definitions = dc.CreateQuery<Definition>("Definitions");
                customer.Definition = definitions.First(p => p.DefID == defID);
            }

            var edu = new EducationSource();
            edu.School = this.Request.Form["Educations-school"];
            edu.Degree = this.Request.Form["Educations-degree"];
            edu.Description = this.Request.Form["Educations-description"];

            var fam = new FamilySource();
            fam.Name = this.Request.Form["FamilyInfo-name"];
            fam.Relationship = this.Request.Form["FamilyInfo-relationship"];
            fam.WorkPlace = this.Request.Form["FamilyInfo-workPlace"];
            fam.Description = this.Request.Form["FamilyInfo-description"];

            var wor = new WorkExprienceSource();
            wor.CompanyName = this.Request.Form["WorkExperience-name"];
            wor.Title = this.Request.Form["WorkExperience-title"];
            wor.StartTime = this.Request.Form["WorkExperience-starttime"];
            wor.EndTime = this.Request.Form["WorkExperience-endtime"];
            wor.Description = this.Request.Form["WorkExperience-description"];

            //CustomerManageHelper.OnCustomerUpdating(customer, edu, fam, wor, null, null);

            var pre = new PreferenceSource();
            pre.List = this.Request.Form["preferenceList"];
            pre.Value = this.Request.Form["preferenceValue"];
            pre.Level = this.Request.Form["preferenceLevel"];

            CustomerManageHelper.OnCustomerUpdating(customer,null, edu, fam, wor, pre, dc);
        }

        protected override void OnEntityAuthorize(EntityMode mode, IEnumerable<DataControlField> fields)
        {

            if (mode == EntityMode.Detail)
            {
                var userRole = LoadRoles();
                fields.First(p => p.AccessibleHeaderText == "Definition").Visible = false;
                fields.First(p => p.AccessibleHeaderText == "Nationality").Visible = false;
                fields.First(p => p.AccessibleHeaderText == "Preference").Visible = false;

                if (userRole.IsOverseaSales)
                {
                    fields.First(p => p.AccessibleHeaderText == "Definition").Visible = true;
                    fields.First(p => p.AccessibleHeaderText == "Nationality").Visible = true;
                    fields.First(p => p.AccessibleHeaderText == "Preference").Visible = true;

                }
            }
        }


        private UserRoles LoadRoles()
        {
            UserRoles right = CompanyInfoHelper.GetUserRightByRoleIDs((this.User as CSPrincipal).Role2s);
            if (!right.IsDomesticAdmin && right.IsDomesticSales && (User as CSPrincipal).AccessLevel == AccessLevel.Write)
                right.IsDomesticCommercial = true;
            return right;
        }

        protected IEnumerable GetEducations(object source)
        {
            return from t in source as IEnumerable<Education>
                   select t;
        }

        protected IEnumerable GetFamilyinfos(object source)
        {
            return from t in source as IEnumerable<FamilyInfo>
                   select t;
        }

        protected IEnumerable GetWorkExperiences(object source)
        {
            return from t in source as IEnumerable<WorkExperience>
                   select t;
        }



        protected void edsCustomer_Inserted(object sender, EntityDataSourceChangedEventArgs e)
        {

            var dc = e.Context;
            var customer = e.Entity as Customer;
            var gender = LogInfoHelper.GetGender(customer.Gender.ToString());
            var title = LogInfoHelper.GetTitle(customer.Title);
            var company = LogInfoHelper.GetCompanyWithCustomer(customer.Company.CompanyID);
            var dep = this.Request.Form["Departmentselect"];
            var department = LogInfoHelper.GetDepartmentName(dep.ToString());
            var email = LogInfoHelper.GetEmail(customer.Email);
            var level = LogInfoHelper.GetLevel(customer.Level.ToString());

            GlobalHelper.LogOperation(this.User.Identity.Name, SystemModule.CIO, "Customer Inserted. id=" +
            customer.CustomerID + "; CustomerName=" + customer.Name + gender + title + company + department +
            email + level);
        }
        protected void edsCustomer_Updated(object sender, EntityDataSourceChangedEventArgs e)
        {
            var dc = e.Context;
            var customer = e.Entity as Customer;
            var gender = LogInfoHelper.GetGender(customer.Gender.ToString());
            var title = LogInfoHelper.GetTitle(customer.Title);
            var company = LogInfoHelper.GetCompanyWithCustomer(customer.Company.CompanyID);
            var dep = this.Request.Form["Departmentselect"];
            var department = LogInfoHelper.GetDepartmentName(dep.ToString());
            var email = LogInfoHelper.GetEmail(customer.Email);
            var level = LogInfoHelper.GetLevel(customer.Level.ToString());

            GlobalHelper.LogOperation(this.User.Identity.Name, SystemModule.CIO, "Customer updated. id=" +
            customer.CustomerID + "; CustomerName=" + customer.Name + gender + title + company + department +
            email + level);
        }


        protected override void OnLoadComplete(EventArgs e)
        {
            base.OnLoadComplete(e);

            if (LogonUser.AccessLevel == AccessLevel.Read)
            {
                var disableField = EntityGrid.Columns.Cast<DataControlField>().
                    FirstOrDefault(p => p is ButtonField && (p as ButtonField).CommandName == "Disable");
                if (disableField != null)
                    disableField.Visible = false;
            }
        }
        /// <summary>
        /// 通过customerID取Gender
        /// </summary>
        protected string GetGender(object gender)
        {
            if (gender == null)
                return "";
            if (Convert.ToBoolean(gender) == true)
                return "Male (男)";
            if (Convert.ToBoolean(gender) == false)
                return "Female (女)";
            return "";
        }

        protected string GetPreferencesValue()
        {
            var value = CustomerManageHelper.GetPreferencesValue();
            return value != "" ? value : "[]";
        }

        protected string GetPreferencesLevel()
        {
            var level = CustomerManageHelper.GetPreferencesLevel();
            return level != "" ? level : "[]";
        }

        protected string GetPreferencesList()
        {
            var list = CustomerManageHelper.GetPreferencesList();
            return list != "" ? list : "[]";
        }

        protected IEnumerable GetCustomerPreference(object source)
        {
            return from t in source as IEnumerable<CustomerPreference>
                   select new
                   {
                       t.LevelID,
                       t.ValueID,
                       t.ListID,
                       ListName = GetListName(t),
                       LevelName = GetLevelName(t),
                       ValueName = GetValueName(t),

                   };
        }

        private string GetListName(CustomerPreference t)
        {
            t.PreferencesListReference.Load();
            return t.PreferencesList.Name;
        }

        private string GetValueName(CustomerPreference t)
        {
            t.PreferencesValueReference.Load();
            return t.PreferencesValue.Name;
        }

        private string GetLevelName(CustomerPreference t)
        {
            t.PreferencesLevelReference.Load();
            return t.PreferencesLevel.Name;
        }

        protected string CheckGender(object obj)
        {
            if (obj == null)
                return "0";
            return Convert.ToBoolean(obj) == true ? "1" : "2";
        }

        protected string GetDefinitionText(object dataItem)
        {
            var definition = dataItem as Definition;
            if (definition == null)
                return string.Empty;
            else
                return definition.Name + (string.IsNullOrEmpty(definition.Description) ? string.Empty : string.Format(" [{0}]", definition.Description));
        }

        protected string GetUser()
        {
            string userName = this.User.Identity.Name;
            return userName;
        }


        [WebMethod]
        public static string GetClusterByCompanyID(string companyID)
        {
            return CustomerManageHelper.GetClusterByCompanyID(int.Parse(companyID));
        }
    }
}
